<?php namespace App\Http\Controllers\Api;

use App\Answer;
use App\Http\Controllers\Controller;
use App\User;
use App\UserInfo;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function userSurvey(Request $request){
        $babyBirthday = $request->get("baby_birthday");
        $answers      = $request->get("answers");
        $address      = $request->get("address");
        $addressInfo  = $request->get("address_info");
        $realname     = $request->get('realname');
        $phone        = $request->get('phone');

        $thatUser = User::wherePhone($phone)->first();

        $province = null;
        $city     = null;
        $area     = null;
        if(!is_null($address)){
            $address = explode(",",$address);
            if(isset($address[0]))$province = $address[0];
            if(isset($address[1]))$city = $address[1];
            if(isset($address[2]))$area = $address[2];
        }

        if(!$thatUser){
            $thatUser = new User();
            $thatUser->phone    = $phone;
            $thatUser->password = bcrypt('123456');
            $thatUser->save();

            $thatUserInfo = new UserInfo();
            $thatUserInfo->baby_birthday = $babyBirthday;
            $thatUserInfo->realname = $realname;
            $thatUserInfo->user_id = $thatUser->id;
            $thatUserInfo->province = $province;
            $thatUserInfo->city     = $city;
            $thatUserInfo->area     = $area;
            $thatUserInfo->detail   = $addressInfo;
            $thatUserInfo->save();
        }else{
            $thatUserInfo = UserInfo::whereUserId($thatUser->id)->first();
            if($thatUserInfo){
                $thatUserInfo->realname      = $realname;
                $thatUserInfo->baby_birthday = $babyBirthday;
                $thatUserInfo->province      = $province;
                $thatUserInfo->city          = $city;
                $thatUserInfo->area          = $area;
                $thatUserInfo->detail        = $addressInfo;
                $thatUserInfo->save();
            }
        }

        if(is_array($answers)){
            if(count($answers) > 0){
                foreach ($answers as $answer){
                    $thatAnswer = Answer::whereQuestionId($answer["q_id"])->whereAnswer($answer["content"])->whereUserId($thatUser->id)->first();
                    if(!$thatAnswer){
                        $thatAnswer = new Answer();
                        $thatAnswer->user_id = $thatUser->id;
                        $thatAnswer->question_id = $answer["q_id"];
                        $thatAnswer->answer = $answer["content"];
                        $thatAnswer->save();
                    }
                }
            }
        }else{
            return response()->json(["level"=>"error","message"=>"数据格式错误"]);
        }


        return response()->json(["level"=>"success","message"=>"提交成功"]);
    }
}